const cryptoJS = require('./cryptoJS')
const rsaJS = require('./rsaJS')

class crypto {

	encryptAES(data, key, iv) {
		try {
			data = cryptoJS.enc.Utf8.parse(data)
			key = cryptoJS.enc.Utf8.parse(key)
			iv = cryptoJS.enc.Utf8.parse(iv)
			const encrypted = cryptoJS.AES.encrypt(data, key, { iv, mode: cryptoJS.mode.CBC, padding: cryptoJS.pad.Pkcs7 })
			return encrypted.toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1068', msg: 'encrypt data failed' }
		}
	}

	decryptAES(data, key, iv) {
		try {
			key = cryptoJS.enc.Utf8.parse(key)
			iv = cryptoJS.enc.Utf8.parse(iv)
			const decrypted = cryptoJS.AES.decrypt(data, key, { iv, mode: cryptoJS.mode.CBC, padding: cryptoJS.pad.Pkcs7 })
			const decryptedStr = decrypted.toString(cryptoJS.enc.Utf8)
			return decryptedStr.toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1069', msg: 'decrypt data failed' }
		}
	}

	encryptRSA(data, key) {
		rsaJS.setPublicKey(key)
		return rsaJS.encrypt(data)
	}

	encryptHMAC(data, key) {
		console.log(cryptoJS)
		const bytes = cryptoJS.HMAC(cryptoJS.SHA1, data, key, {
			asBytes: true
		})
		return cryptoJS.util.bytesToBase64(bytes)
	}

	md5(data) {
		try {
			return cryptoJS.MD5(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1058', msg: 'encrypt data failed' }
		}
	}

	sha1(data) {
		try {
			return cryptoJS.SHA1(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1055', msg: 'encrypt data failed' }
		}
	}

	sha256(str) {
		try {
			return cryptoJS.SHA256(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1056', msg: 'encrypt data failed' }
		}
	}

	sha512(str) {
		try {
			return cryptoJS.SHA512(data).toString()
		}
		catch (err) {
			console.error(err)
			throw { code: '-1056', msg: 'encrypt data failed' }
		}
	}

	encodeBase64(data) {
		console.log(data, this.string2buffer(data))
		const base64 = wx.arrayBufferToBase64(this.string2buffer(data))
		console.log(base64)
		return base64
	}

	decodeBase64(data) {
		const buffer = wx.base64ToArrayBuffer(data)
		console.log(buffer, data)
		return String.fromCharCode.apply(null, new Unint8Array(buffer))
	}

	//字符串转ArrayBuffer
	string2buffer(str) {
		// 首先将字符串转为16进制
		let val = ""
		for (let i = 0; i < str.length; i++) {
			if (val === '') {
				val = str.charCodeAt(i).toString(16)
			}
			else {
				val += ',' + str.charCodeAt(i).toString(16)
			}
		}
		// 将16进制转化为ArrayBuffer
		return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
			return parseInt(h, 16)
		})).buffer
	}

}

module.exports = new crypto